﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using BussinessLogic.Models.Account;
using BussinessLogic.Services;
using System.Net.Mail;
using System.Net;
using BussinessLogic;
using BussinessLogic.Helpers;


namespace AspMVCProject.Controllers
{
    public class AccountController : Controller
    {
        #region LogOn

        public ActionResult LogOn()
        {
            return View();
        }


        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                AccountService.AccountState accountState = AccountService.ValidateUser(model);
                if (accountState == AccountService.AccountState.EmailNotExist)
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
                else if (!accountState.HasFlag(AccountService.AccountState.CorrectPassword))
                {
                    ModelState.AddModelError("", "Your password is incorrect.");
                }
                else if (!accountState.HasFlag(AccountService.AccountState.ActiveAccount))
                {
                    //ModelState.AddModelError("", "Your account is blocked.");
                    return View("AccountLocked");
                }
                else
                {
                    // user is valid
                    FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
            }

            // If we got this far, something was incorrect, redisplay form
            return View(model);
        }

        public ActionResult AccountLocked()
        {
            return View();
        }


        #endregion

        #region LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }
        #endregion

        #region Register

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                Guid? activationHash = AccountService.RegisterUser(model);

                if (activationHash != null)
                {
                    EmailHelper.SendConfirmationEmail(model.Email, model.FirstName + " " + model.LastName, activationHash);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(MembershipCreateStatus.DuplicateUserName));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        #endregion

        #region Admin register

        public ActionResult AdminRegister(string email, string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return View("Error");
            }

            RegisterModel model = new RegisterModel { Email = email, Key = key };
            return View(model);
        }

        [HttpPost]
        public ActionResult AdminRegister(RegisterModel model)
        {
            if (string.IsNullOrEmpty(model.Key))
            {
                return View("Error");
            }

            if (ModelState.IsValid)
            {
                // Attempt to register the user
                bool valid = AccountService.CompleteRegisterAdmin(model);

                if (valid)
                {
                    return RedirectToAction("Index", "Home");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        #endregion

        #region Verify

        public ActionResult Verify(string email, string key)
        {
            bool activate = AccountService.ActivateUser(email, new Guid(key));

            if (activate)
            {
                VerifyModel verifyModel = new VerifyModel { Message = "You have successfully activated your account" };
                FormsAuthentication.SetAuthCookie(email, false /* createPersistentCookie */);
                return View(verifyModel);
            }
            else
            {
                VerifyModel verifyModel = new VerifyModel { Message = "Your activation link is not valid" };
                return View(verifyModel);
            }
        }
        #endregion

        #region RecoverPassword

        public ActionResult RecoverPassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult RecoverPassword(RecoverPasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (AccountService.FindActiveUser(model.Email))
                {
                    Guid? recoverHash = AccountService.SetRecoverPassword(model.Email);
                    EmailHelper.SendChangePasswordEmail(model.Email, "", recoverHash);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", "The email provided is incorrect.");
                }
            }

            return View(model);
        }
        #endregion

        #region ChangePassword

        public ActionResult ChangePassword(string email, string key)
        {
            if (!string.IsNullOrEmpty(email) || !string.IsNullOrEmpty(key))
            {
                if (AccountService.VerifyRecoverPassword(email, new Guid(key)))
                {
                    return View();
                }
            }

            return View("Error");
        }

        [HttpPost]
        public ActionResult ChangePassword(RecoverChangePasswordModel model, string email, string key)
        {
            if (ModelState.IsValid)
            {
                if (AccountService.ChangePassword(email, model.NewPassword, model.ConfirmPassword))
                {
                    return View("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            return View(model);
        }
        #endregion

        #region ChangeAuthenticatedUserPasssword
        [Authorize]
        public ActionResult ChangeUserPassword()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangeUserPassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                bool changePasswordSucceeded = AccountService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword, model.ConfirmPassword);

                if (changePasswordSucceeded)
                {
                    return View("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        #endregion

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
